package top.maof.book.controller;

import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.maof.book.annotation.Hot;
import top.maof.book.aspect.HotAspect;
import top.maof.book.model.Likes;
import top.maof.book.result.Result;
import top.maof.book.service.BookInfoService;
import top.maof.book.service.LikesService;
import top.maof.book.type.HotType;
import top.maof.book.utils.JWTUtils;

@RestController
@RequestMapping("/likes")
public class LikesController {
    @Autowired
    BookInfoService bookInfoService;

    @Autowired
    LikesService likesService;

    @ApiOperation("个人对此书是否点过赞")
    @GetMapping("isExit")
    public Result has(@RequestHeader("token") String token, Integer bookId) throws Exception {
        int useId = Integer.parseInt(JWTUtils.parseToken(token, "id"));
        boolean exist = likesService.isExist(useId, bookId);
        if (exist) {
            return Result.success(true);
        } else {
            return Result.success(false);
        }
    }

    @ApiOperation("移除个人点赞书的记录")
    @GetMapping("deleteProfile")
    @Hot(value = "#bookId", type = HotType.LIKES, keepType = "sub")
    public Result delete(Integer bookId, @RequestHeader("token") String token) throws Exception {

        int useId = Integer.parseInt(JWTUtils.parseToken(token, "id"));

        likesService.remove(useId, bookId);
        return Result.success();
    }

    @ApiOperation("个人点赞")
    @GetMapping("addProfile")
    @Hot(value = "#bookId", type = HotType.LIKES, keepType = "add")
    public Result add(Integer bookId, @RequestHeader("token") String token) throws Exception {
        int useId = JWTUtils.getUserId(token);
        Likes likes = new Likes();
        likes.setBookId(bookId);
        likes.setUserId(useId);
        likes.setTime(System.currentTimeMillis());

        boolean save = likesService.save(likes);


        if (save) {
            return Result.success();
        }
        return Result.response_500();
    }

    // 获取书的点赞数
    @GetMapping("likesNum")
    @ApiOperation("书的点赞数")
    public Result bookCount(Integer bookId) throws Exception {
        int i = likesService.likesNum(bookId);
        return Result.success(i);
    }
}
